package com.ice.framework.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.ice.framework.event.NullEvent
import com.ice.framework.utils.ToastUtil
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

abstract class BaseFragment<T:BaseViewModel,T1: ViewBinding> : Fragment() {

    lateinit var viewModel: T

    lateinit var binding : T1

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun onNull(nullEvent: NullEvent){}

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        if(!EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().register(this)
        }
        binding=initViewBinding(inflater,container)
        viewModel= ViewModelProvider(this).get(initViewModel())
        viewModel.toastMsg.observe(viewLifecycleOwner) {
            ToastUtil.show(it)
        }
        initObserver()
        initView()
        return binding.root
    }

    override fun onDestroyView() {
        EventBus.getDefault().unregister(this)
        super.onDestroyView()
    }

    abstract fun initViewModel():Class<T>

    abstract fun initViewBinding(inflater: LayoutInflater,container: ViewGroup?):T1

    override fun onResume() {
        super.onResume()
        initData()
    }

    //初始化监听
    abstract fun initObserver()

    //初始化数据
    abstract fun initData()

    //初始化View
    abstract fun initView()


}
